package com.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 一个小菜逼
 * @Date: 2020/4/22
 */
public class MyLock {

    public static void main(String[] args) {
        DataSource dataSource = new DataSource();

        new Thread(()->{
            dataSource.increase();
        }).start();

        new Thread(()->{
            dataSource.decrease();
        }).start();

        new Thread(()->{
            dataSource.printStr();
        }).start();
    }
}

class DataSource{

    ReentrantLock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    int target=0;

    public void increase(){
        lock.lock();
        target++;
        System.out.println(target);
        //唤醒等待的condition2
        condition2.signal();
        lock.unlock();
    }

    public void decrease(){
        lock.lock();
        try {
            //不加判断条件会被阻塞，await方法上面要加上while循环，if可能造成虚假唤醒
            while (target!=1)
            //condition2等待
            condition2.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        target--;
        System.out.println(target);
        //唤醒等待的condition3
        condition3.signal();
        lock.unlock();
    }

    public void printStr(){
        lock.lock();
        try {
            //不加判断条件会被阻塞，await方法上面要加上while循环，if可能造成虚假唤醒
            while (target!=0)
            //condition3等待
            condition3.await();
            System.out.println("第一轮执行完毕");
            //唤醒等待的condition1
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       lock.unlock();
    }
}
